package com.jstyle.jclifexd.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import com.jstyle.countrylibrary.CountryPage;
import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.model.Activitvtiesmsg;
import com.jstyle.jclifexd.model.Createdmode;
import com.jstyle.jclifexd.utils.RxBus;
import com.jstyle.jclifexd.utils.ScreenUtils;
import com.jstyle.jclifexd.utils.SharedPreferenceUtils;
import com.jstyle.jclifexd.utils.StatusBarUtil;
import com.jstyle.jclifexd.utils.Utils;
import com.jstyle.jclifexd.view.BottomDialog;
import com.jstyle.jclifexd.view.EditTextWithDelete;
import com.mob.tools.FakeActivity;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.SMSSDK;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 创建活动 2
 */
public class CreateActivitiestwoActivity extends BaseActivity {

    @BindView(R.id.Phone_name)
    EditTextWithDelete Phone_name;
    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.description)
    EditText description;

    @BindView(R.id.not_limited)
    Button not_limited;

    @BindView(R.id.getCountryCode)
    Button btLoginGetCountryCode;


    @BindView(R.id.creat_switch)
    Switch creat_switch;
    private String countryCode = "001-";
    Createdmode createdmode;
    BottomDialog sportdailog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题栏
        setContentView(R.layout.activity_cretetwo);
        StatusBarUtil.setRootViewFitsSystemWindows(this,true);
        StatusBarUtil.setTranslucentStatus(this);
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            StatusBarUtil.setStatusBarColor(this,0x55000000);
        }
        ButterKnife.bind(this);
        sportdailog= new BottomDialog(CreateActivitiestwoActivity.this, R.layout.dialog_numbertype);
        if(null!=getIntent().getSerializableExtra("createdmode")){
            createdmode= (Createdmode) getIntent().getSerializableExtra("createdmode");
            createdmode.setAudit(false);
            createdmode.setNumber(9999);
            creat_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    createdmode.setAudit(isChecked);
                }
            });
            countryCode= SharedPreferenceUtils.getString(SharedPreferenceUtils.KEY_countryCode, getString(R.string.DefaultCountryCode));
        }

    }


    private void getCountryCode() {
        CountryPage phone = new CountryPage();
        phone.setCountryId("1");
        phone.showForResult(CreateActivitiestwoActivity.this, (Intent) null, new FakeActivity() {
            @Override
            public void onResult(HashMap<String, Object> data) {
                super.onResult(data);
                String currentId = (String) data.get("id");
                int result = (int) data.get("result");
                if (result == CountryPage.Result_OK) {
                    String[] res = SMSSDK.getCountry(currentId);
                    btLoginGetCountryCode.setText("+" + res[1]);
                    countryCode = "00" + res[1] + "-";
                }
            }
        });
    }


    @OnClick({R.id.iv_back,R.id.create2_nextstep,R.id.not_limited,R.id.getCountryCode})
    public void onViewClicked(View view) {
        if(Utils.isFastClick()){return;}
        switch (view.getId()) {
            case R.id.getCountryCode:
                getCountryCode();
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.create2_nextstep:
                if(TextUtils.isEmpty(Phone_name.getText())){
                    showToast(getResources().getString(R.string.login_input_phone));
                    return;
                }
                if(TextUtils.isEmpty(name.getText())){
                    showToast(getResources().getString(R.string.yourreal_name));
                    return;
                }
                createdmode.setCreaterPhone(countryCode +Phone_name.getText().toString());
                createdmode.setCreaterName(name.getText().toString());
                if(0==createdmode.getNumber()){
                    showToast(getResources().getString(R.string.setting_number));
                    return;
                }
                if(TextUtils.isEmpty(description.getText())){
                    showToast(getResources().getString(R.string.description));
                    return;
                } else{
                    createdmode.setDetail(description.getText().toString().trim());
                }
                Commit(createdmode);
                break;
            case R.id.not_limited:
                if (sportdailog.isshoeww()) {
                    sportdailog.dismiss();
                } else {
                    sportdailog.show();
                    sportdailog.setWithandHeight(CreateActivitiestwoActivity.this, ScreenUtils.dip2px(this, 350));
                    getviewByptype();
                }

                break;

        }
    }


    int type=4;
    private void getviewByptype() {
        final EditText secelt_run = sportdailog.getmView().findViewById(R.id.input_number);
        final Button ershi_Button = sportdailog.getmView().findViewById(R.id.ershi_Button);
        final Button wushi_Button = sportdailog.getmView().findViewById(R.id.wushi_Button);
        final Button not_conmit = sportdailog.getmView().findViewById(R.id.not_conmit);
        secelt_run.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showSoftInput(secelt_run,true);
                } else {
                    showSoftInput(secelt_run,false);
                }
            }
        });
        secelt_run .addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                type=1;
                Settingback(ershi_Button);
                Settingback(wushi_Button);
                Settingback(not_conmit);
            }
            @Override
            public void afterTextChanged(Editable s) { }
        });



        ershi_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type=2;
                ershi_Button.setBackground(getResources().getDrawable(R.drawable.bg_nunberbule));
                Settingback(wushi_Button);
                Settingback(not_conmit);
            }
        });
        wushi_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type=3;
                wushi_Button.setBackground(getResources().getDrawable(R.drawable.bg_nunberbule));
                Settingback(ershi_Button);
                Settingback(not_conmit);
            }
        });

        not_conmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type=4;
                not_conmit.setBackground(getResources().getDrawable(R.drawable.bg_nunberbule));
                Settingback(ershi_Button);
                Settingback(wushi_Button);
            }
        });
        final Button conmit_ok = sportdailog.getmView().findViewById(R.id.conmit_ok);

        conmit_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (type){
                    case 1:
                        if(TextUtils.isEmpty(secelt_run.getText())||0==Integer.valueOf(secelt_run.getText().toString())){
                            return;
                        }
                        not_limited.setText(Long.valueOf(secelt_run.getText().toString())+"");
                        createdmode.setNumber(Long.valueOf(secelt_run.getText().toString()));
                        break;
                    case 2:
                        createdmode.setNumber(20);
                        not_limited.setText("20");
                        break;
                    case 3:
                        createdmode.setNumber(50);
                        not_limited.setText("50");
                        break;
                    case 4:
                        createdmode.setNumber(9999);
                        not_limited.setText(getResources().getString(R.string.not_limited));
                        break;

                }
                sportdailog.dismiss();

            }
        });


    }

    /**
     * 自动获取焦点并弹出软键盘
     * @param value 开或关闭软键盘
     */
    public void showSoftInput(final EditText etIpAddress,Boolean value) {
        if(value){
            //自动获取焦点
            etIpAddress.setFocusable(true);
            etIpAddress.setFocusableInTouchMode(true);
            etIpAddress.requestFocus();
            etIpAddress.requestFocus();
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imm.showSoftInput(etIpAddress, InputMethodManager.SHOW_IMPLICIT);
        }else{
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            View v = getWindow().peekDecorView();
            if (null != v) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }

    }




    private   void Commit(Createdmode date){
        Map<String, Object> map = new HashMap<>();
        map.put("uid", NetWorkUtil.getUserId());
        map.put("start",date.getStart());
        map.put("end", date.getEnd());
        map.put("signupTime", date.getSignupTime());
        map.put("type", "act");
        map.put("sportType", date.getSportType());
        map.put("title", date.getTitle());
        map.put("imgUrl", date.getImgUrl());
        map.put("address", date.getAddress());
        map.put("createrName", date.getCreaterName());
        map.put("number", date.getNumber());
        map.put("createrPhone", date.getCreaterPhone());
        map.put("audit", date.isAudit()?"yes":"no");
        map.put("detail", date.getDetail());
        NetWorkUtil.getInstance().getJstyleApi().create(map).
                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Activitvtiesmsg>() {
            @Override
            public void onSubscribe(Disposable d) { }
            @Override
            public void onNext(Activitvtiesmsg activitvtiesData) {
                if(activitvtiesData.getMsgCode()==1){
                    showToast(getResources().getString(R.string.created_successfully));
                    RxBus.getInstance().post("reload");
                    finish();
                }else if(7306==activitvtiesData.getMsgCode()){
                    showToast(getResources().getString(R.string.created_after));
                    finish();
                }else{
                    showToast(getResources().getString(R.string.created_failed));
                    finish();
                }
             //   Log.e("sdasda",activitvtiesData.toString());
            }
            @Override
            public void onError(Throwable e) {
                Log.e("sdasda",e.toString());
            }
            @Override
            public void onComplete() { }
        });
    }





    private void Settingback(View view){
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackgroundDrawable(null);
        } else {
            view.setBackground(null);
        }
    }


}
